package com.knowledge.plus.自定义异常.service;

import com.knowledge.plus.自定义异常.MyException;
import com.knowledge.plus.自定义异常.ResultBody;
import com.knowledge.plus.自定义异常.enums.CommonEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.sql.BatchUpdateException;
import java.sql.SQLSyntaxErrorException;

/**
 * 自定义全局异常处理类
 * ====== 注：该类必须要和捕获的Controller接口写在同一个模块中（该类和所调的接口在同一个模块中） ======
 *
 * @author PF.Tian
 * @since 2021/09/13
 */
@Slf4j
//@RestControllerAdvice = @ControllerAdvice + @ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ResultBody myExceptionHandler(HttpServletRequest req, MyException e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！原因是:", e);
        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }


    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e) {
        log.error("未知异常！原因是:", e);
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * SQL 异常捕获
     */
    @ExceptionHandler({BadSqlGrammarException.class, BatchUpdateException.class, SQLSyntaxErrorException.class})
    // @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)   // 添加该注解时，该方法仅返回 “系统接口500异常”
    public ResultBody sendErrorResponse_UserDefined(Exception e){
        log.error(e.getMessage());
        return ResultBody.error("SQL 语法错误：" + e.getCause());
    }


}
